package dao.impl;

import dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import pojo.User;
import util.MyBatisUtil;

import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll(User user) {
//        //定义mybatis核心配置文件
//        String resource = "mybatis-config.xml";
//        SqlSession sqlSession = null;
//        // 加载配置文件
//        try {
//            // 流操作
//            InputStream inputStream = Resources.getResourceAsStream(resource);
//            // 创建会话工厂
//            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//            // 创建会话
//            sqlSession = sqlSessionFactory.openSession();
//            // 执行数据库操作
//            List<User> users = sqlSession.getMapper(UserDao.class).findAll();
//            return users;
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        } finally {
//            sqlSession.close();
//        }
        return MyBatisUtil.getSession().getMapper(UserDao.class).findAll(user);
    }

    @Override
    public int addUser(User user) {
        SqlSession session = MyBatisUtil.getSession();
        int result=session.getMapper(UserDao.class).addUser(user);
        //提交事务
        session.commit();
        return result;
    }

    @Override
    public User findById(Integer id) {
        return MyBatisUtil.getSession().getMapper(UserDao.class).findById(id);
    }//5

    @Override
    public int updateUser(User user) {
        //增删改与新增一样，需要提交
        SqlSession session = MyBatisUtil.getSession();
        int result=session.getMapper(UserDao.class).updateUser(user);
        //提交事务
        session.commit();
        return result;
    }

    @Override
    public int deleteUserById(Integer id) {
        SqlSession session = MyBatisUtil.getSession();
        int result=session.getMapper(UserDao.class).deleteUserById(id);
        //提交事务
        session.commit();
        return result;
    }

}
